package leetcode.L500;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Ex56_merge {
    public static void main(String[] args) {

        int[][] intervals = {{1,3},{2,6},{8,10},{15,18}};
        int[] newintervals = {9,16};
        int first,second;
        int n = intervals.length;

        int[][] temp = new int[n+1][1];
        System.arraycopy(intervals,0,temp,0,n);
        temp[n] = newintervals;
        intervals = temp;
        n++;

        if(n<2){
            System.out.print(intervals);
        }
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));
        //重点！根据第一个排序
        List<int[]> merged = new ArrayList<int[]>();
        first = intervals[0][0];
        second = intervals[0][1];

        for (int i = 1; i < n ; i++) {
            if(intervals[i][0]>second){
                merged.add(new int[]{first,second});
                first = intervals[i][0];
                second = intervals[i][1];
            }
            else if(intervals[i][1]>second){
                second = intervals[i][1];
            }
        }
        merged.add(new int[]{first,second});

        int res[][] = new int[merged.size()][1];
        res = merged.toArray(new int[merged.size()][]);

        System.out.print(res);
    }
}
